$m(function(args){
	var $this = this.element,
		that = this,
		//下方的表格
		grid = $this.find("#tempo-webapi-code-grid"),
		//表格数据，通过表格数据可以判断新的客户端标识是否已存在，如果已存在，则不再刷新表格
		gridData = null,
		fillback = args.fillback;
	
	var locale = function(l){
		return TempoUtils.locale("webapi."+l);
	}
	
	var dialogTitle = locale("api_info_title"); 
	
	function initDialog(){
		$this.dialog({
			width:650,
			height:520, 
			resizable:false, 
			title:dialogTitle,
			modal:true,  
			close:function(){
				$(this).remove();
			},
			open:function(){
				renderComp(); 
				$this.scroll(function(){
					$this.find("input[name='clientCode']").validatebox("refreshToolTip");
					$this.find("input[name='clientName']").validatebox("refreshToolTip");
				});
				
				renderGrid(fillback.apiId);
			},
			buttons:[{
				text: locale("cancel"), //'取消',
				click:function(){
					$this.dialog("close"); 
				}
			}]
		})
	}
	function renderComp(){
		TempoUtils.parserUi($this, fillback || {});
		for(var o in fillback){
			$this.find("#"+o).html(fillback[o]);
		}
		
		$("#genSkCode").click(function(){
			genSkCode();
		});
	}  
	/**
	 * 生成调用码
	 */
	function genSkCode(){
		var form = $this.find("form");
		if(!form.formValidate()){
			return; 
		}  
		var formData = TempoUtils.getRecord(form);
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath+"/api/ai/webcode/gen",
			data:{
				apiId:formData.apiId,
				clientCode:formData.clientCode
			},
			type:'post', 
			dataType:'json',
			complete:function(){
				progress.tempoprogressbar("destroy");
			},
			success:function(result){
				$this.find("#skCode").html(result.data);
				//exists promise 以及判断重复机制是前边人写的…改不动,影响前台多
				isExists(formData.apiId,formData.clientCode,formData.clientName)
					.then(function(r){
						if(r){
							TempoUtils.showTip(TempoUtils.locale("webapi.clientCodeExist"));
						}
					},function(r){
						if(!r){
							save(formData,result.data);
						}else{
							TempoUtils.showTip(TempoUtils.locale("webapi.clientNameExist"));
						}
					});
			},
			error:function(){
				
			}
		});
	}
	
	function save(formData,skCode){
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath+"/api/ai/webcode/save",
			type:'post',
			data:{
				apiId:formData.apiId,
				clientCode:formData.clientCode,
				skCode:skCode,
				clientName : formData.clientName,
				status:1,
				desc:""
			},
			success:function(result){
				progress.tempoprogressbar("destroy");
				if(result){
					grid.datagrid("reloadGrid");
				}
			},
			error:function(){
				progress.tempoporogressbar("destroy");
			}
		});
	}
	
	/**
	 * 判断编码是否已存在
	 */
	function isExists(apiId,code,name){
		if(gridData!=null){
			return new Promise(function(resolve,reject){
				var exist = false;
				var tagName = false;
				for(var i=0,len=gridData.length;i<len;i++){
					if(gridData[i].clientCode ===code){
						exist = true;
						break;
					}
					if(gridData[i].clientName === name){
						tagName = true;
						break;
					}
				}
				if(exist){
					resolve(exist);
				}else{
					reject(tagName);
				}
			})	
		}else{
			return new Promise(function(resolve,reject){
				var progress = $("<div/>").tempoprogressbar();
				$.ajax({
					url:contextPath+'/api/ai/webcode/exist',
					type:'post',
					dataType:'json',
					data:{
						apiId:apiId,
						code:code
					},
					success:function(result){
						reject(result.data);
					},
					error:function(e){
						reject(e);
					}
				}).done(function(){
					progress.tempoprogressbar("destroy");
				})
			});
		}
	}
	
	/**
	 * 渲染表格
	 */
	function renderGrid(apiId){
		grid.datagrid({
			url:contextPath+"/api/ai/webcode/list-apicode-infos",
			datatype:'json',
			fit:true, 
			rownumbers : true,
			multiselect:false,   
			separator:false, 
			rowNum:1000, 
			postData:{
				apiId:apiId
			},
			colNames:['id','apiId',TempoUtils.locale("webapi.client_code"),TempoUtils.locale("webapi.sk_code"),TempoUtils.locale("webapi.clientName"),TempoUtils.locale("webapi.state"),TempoUtils.locale("webapi.operation")],
			colModel:[{
				name:'id',
				hidden:true
			},{
				name:'apiId',
				hidden:true
			},{
				name:'clientCode',
				sortable:false
			},{
				name:'skCode',
				sortable:false
			}, {
				name : 'clientName',
				sortable : false
			},{
				name:'status',
				sortable:false,
				formatter:function(val){
					return val=='1'?TempoUtils.locale("webapi.enable"):TempoUtils.locale("webapi.disable");
				}
			},{
				name:'action',
				buttons:[{
					id:'disable',
					title:TempoUtils.locale("webapi.disable"),
					icon:'ui-icon tempo-ui-icon tempo-ui-icon-disabled',
					click:function(e,dt){
						var code = dt.rowData.clientCode
						$.ajax({
							url : contextPath + "/api/ai/mine/publish/checkAuthCode",
							data : {
								authid:code
							},
							success : function(result) {
								if(!result){
									updateStatus(dt.rowData.apiId,code,false);
								}else{
									$("<div/>").confirm({
										title :  TempoUtils.locale("mine.prompt"), 
										msg :  TempoUtils.locale("mine.authId_disable_tip"),
										height : 240,
										width : 300,
										ok : function(){
											var process = $("<div/>").tempoprogressbar();
											updateStatus(dt.rowData.apiId,code,false);
										}
									});
								}
							}
						})
					},
					beforeAdd:function(rowId,rowData){
						return rowData.status=="1";
					}
				},{
					id:'enable',
					title:TempoUtils.locale("webapi.enable"),
					icon:'ui-icon tempo-ui-icon tempo-ui-icon-lock',
					beforeAdd:function(rowId,rowData){
						return rowData.status=="0";
					},
					click:function(e,dt){
						updateStatus(dt.rowData.apiId,dt.rowData.clientCode,true);
					}
				},{
					id:'remove',
					title:TempoUtils.locale("webapi.delete"),
					icon:'ui-icon tempo-ui-icon tempo-ui-icon-remove',
					click:function(e,dt){
						var code = dt.rowData.clientCode
						$.ajax({
							url : contextPath + "/api/ai/mine/publish/checkAuthCode",
							data : {
								authid:code
							},
							success : function(result) {
								if(!result){
									removeClientCode(dt.rowData.apiId,code); 
								}else{
									$("<div/>").confirm({
										title :  TempoUtils.locale("mine.prompt"), 
										msg :  TempoUtils.locale("mine.authId_delete_tip"),
										height : 240,
										width : 300,
										ok : function(){
											var process = $("<div/>").tempoprogressbar();
											removeClientCode(dt.rowData.apiId,code); 
										}
									});
								}
							}
						})
					}
				}]
			}],
			fit:true,
			loadComplete:function(xhr){
				gridData = xhr.rows;
			}
		})
	}
	
	/**
	 * 更新状态
	 */
	function updateStatus(apiId,clientCode,status){
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath+"/api/ai/webcode/update",
			data:{
				apiId:apiId,
				clientCode:clientCode,
				status:status
			},
			type:'post',
			success:function(result){
				if(result){
					grid.datagrid("reloadGrid");
				}
			}
		}).done(function(){
			progress.tempoprogressbar("destroy");
		})
	}
	
	/**
	 * 删除客户端调用码
	 */
	function removeClientCode(apiId,clientCode){
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath+"/api/ai/webcode/remove-client-code",
			data:{
				apiId:apiId,
				clientCode:clientCode
			},
			type:'post',
			success:function(result){
				if(result){
					grid.datagrid("reloadGrid");
				}
			}
		}).done(function(){
			progress.tempoprogressbar("destroy");
		})
	}
	
	
	(function(){
		initDialog();
	}.call(this));
	
}); 